<template>
  <div class="department-container">
    <el-card>
      <div class="header">
        <h2>部门管理</h2>
        <el-button type="primary" @click="handleAdd">新增部门</el-button>
      </div>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="deptName" label="部门名称" width="180" />
        <el-table-column prop="managerName" label="部门主管" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.deptId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form">
        <el-form-item label="部门ID" v-if="isEdit">
          <el-input v-model="form.deptId" disabled />
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input v-model="form.deptName" />
        </el-form-item>
        <el-form-item label="部门主管">
          <el-select v-model="form.managerId" placeholder="请选择部门主管">
            <el-option
                v-for="user in users"
                :key="user.userId"
                :label="user.userName"
                :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getDepartments,
  addDepartment,
  updateDepartment,
  deleteDepartment
} from '@/api/departments';
import { getUsers } from '@/api/users';

export default {
  setup() {
    const loading = ref(false);
    const tableData = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增部门');
    const form = ref({
      deptId: '',
      deptName: '',
      managerId: ''
    });
    const isEdit = ref(false);
    const users = ref([]); // 存储用户列表

    // 获取用户列表
    const fetchUsers = async () => {
      try {
        const res = await getUsers();
        if (!Array.isArray(res)) {
          throw new Error('API返回的用户数据不是数组格式');
        }
        users.value = res;
      } catch (error) {
        ElMessage.error('获取用户列表失败: ' + error.message);
      }
    };

    // 获取部门列表
    const fetchDepartments = async () => {
      loading.value = true;
      try {
        const res = await getDepartments();
        const dataArray = res.data || res; // 可能是 res.data 包含数组
        if (!Array.isArray(dataArray)) {
          throw new Error('API返回的部门数据不是数组格式');
        }

        // 获取用户列表匹配主管名字
        await fetchUsers();

        // 将部门数据与用户列表关联，添加managerName属性
        tableData.value = dataArray.map(dept => {
          // 在用户列表中查找该部门的主管
          const manager = users.value.find(user => user.userId === dept.managerId);
          return {
            ...dept,
            managerName: manager ? manager.userName : '未知' // 如果找到主管则显示主管名字，否则显示未知
          };
        });
      } catch (error) {
        ElMessage.error('获取失败: ' + (error.message || '未知错误'));
      } finally {
        loading.value = false;
      }
    };

    // 新增部门
    const handleAdd = () => {
      dialogTitle.value = '新增部门';
      isEdit.value = false;
      form.value = {
        deptId: '',
        deptName: '',
        managerId: ''
      };
      dialogVisible.value = true;
    };

    // 编辑部门
    const handleEdit = (row) => {
      dialogTitle.value = '编辑部门';
      isEdit.value = true;
      // form.value = { ...row };
      form.value = {
        deptId: row.deptId,
        deptName: row.deptName,
        managerId: row.managerId
      };
      dialogVisible.value = true;
    };

    // 删除部门
    const handleDelete = (deptId) => {
      ElMessageBox.confirm('确认删除该部门吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteDepartment(deptId);
          ElMessage.success('删除成功');
          fetchDepartments();
        } catch (error) {
          ElMessage.error('删除失败: ' + error);
        }
      }).catch(() => {});
    };

    // 提交表单
    const handleSubmit = async () => {
      try {
        // 表单验证
        if (!form.value.deptName) {
          ElMessage.warning('部门名称不能为空');
          return;
        }

        if (isEdit.value) {
          // 编辑：传递所有字段
          await updateDepartment({
            deptId: form.value.deptId,
            deptName: form.value.deptName,
            managerId: form.value.managerId
          });
          ElMessage.success('更新成功');
        } else {
          // 新增：只传递必要字段，不传递deptId
          await addDepartment({
            deptName: form.value.deptName,
            managerId: form.value.managerId
          });
          ElMessage.success('新增成功');
        }

        dialogVisible.value = false;
        fetchDepartments();
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败: ' + error : '新增失败: ' + error);
      }
    };

    onMounted(() => {
      fetchDepartments();
    });

    return {
      users,

      tableData,
      dialogVisible,
      dialogTitle,
      form,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit
    };
  }
};
</script>

<style scoped>
.department-container {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>